package com.xinyue.exceltool.logic;

import com.alibaba.fastjson.JSON;
import com.google.common.hash.Hashing;
import com.xinyue.exceltool.config.ExcelToolConfig;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
public class TableMd5Manager {
    @Autowired
    private ExcelToolConfig excelToolConfig;
    private Logger logger = LoggerFactory.getLogger(TableMd5Manager.class);
    private static final String FILE_NAME = "tableMd5.json";

    public void createTableMd5() throws IOException {
        File jsonDir = new File(excelToolConfig.getServerDataPath());
        /**
         * 存储每个表json文件的md5值，key是表名，value是表的内容md5值
         */
        Map<String, String> tableMd5Map = new HashMap<>();
        for (File file : jsonDir.listFiles()) {
            try {
                if (file.getName().endsWith(FILE_NAME)) {
                    continue;
                }
                byte[] bytes = FileUtils.readFileToByteArray(file);
                String value = Hashing.hmacMd5(bytes).newHasher().hash().toString();
                tableMd5Map.put(file.getName(), value);
            } catch (Exception e) {
                logger.warn("读取文件失败", e);
            }
        }
        writeFile(tableMd5Map);
    }

    private void writeFile(Map<String, String> data) throws IOException {
        String path = excelToolConfig.getServerDataPath() + "/" + FILE_NAME;
        File file = new File(path);
        file.delete();
        FileUtils.write(file, JSON.toJSONString(data), StandardCharsets.UTF_8);
    }
}
